package com.smartystars.quizzer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.smartystars.quizzerServer.ExternalStorage;
import com.smartystars.ui.SlideMenu.SlideMenuItem;
import com.smartystars.ui.SlideMenu;
import com.smartystars.ui.SlideMenuInterface.OnSlideMenuItemClickListener;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class MultiplayerStartupActivity extends Activity implements OnSlideMenuItemClickListener, OnGestureListener {
	
	private UUID deviceUuid;
	protected ProgressDialog Progressdialog;
	private Handler responseHandler = new Handler();
	private Handler loginHandler = new Handler();
	private SlideMenu slidemenu;
	private HashMap<String ,Integer > friendMap= new HashMap<String,Integer>();
	private int friendPosition = 0;
	private LinearLayout lilay;
	protected GestureDetector gestureScanner;
	private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private boolean savelogin = false;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_multiplayer_startup);
		generateDeviceId();
		createStartupDialog();
		slidemenu = (SlideMenu)findViewById(R.id.slideMenu);
		gestureScanner = new GestureDetector(this);

		
	   
	}


	@Override
	public boolean onTouchEvent(MotionEvent me){
		return gestureScanner.onTouchEvent(me);
	}
	public boolean onDown(MotionEvent e){
		return true;
	}
	public boolean onFling(MotionEvent e1,MotionEvent e2,float velocityX,float velocityY){
		try {
            if(e1.getX() > e2.getX() && Math.abs(e1.getX() - e2.getX()) > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
              //  Toast.makeText(this.getApplicationContext(), "Left", Toast.LENGTH_SHORT).show();
            	slidemenu.hide();
                
            }else if (e1.getX() < e2.getX() && e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
               // Toast.makeText(this.getApplicationContext(), "Right", Toast.LENGTH_SHORT).show();
            	slidemenu.show();
            }
        } catch (Exception e) {
            // nothing
        }
        return true;
		
	}
	public void onLongPress(MotionEvent e){}
	
	public boolean onScroll(MotionEvent e1,MotionEvent e2,float distanceX,float distanceY){
		return true;
	}
	public void onShowPress(MotionEvent e){}
	public boolean onSingleTapUp(MotionEvent e){ return true;}

	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.multiplayer_startup, menu);
		return true;
	}
	
	
	private void generateDeviceId() {
	    final String macAddr, androidId;

	    WifiManager wifiMan = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
	    WifiInfo wifiInf = wifiMan.getConnectionInfo();

	    macAddr = wifiInf.getMacAddress();
	    androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

	     deviceUuid = new UUID(androidId.hashCode(), macAddr.hashCode());

	    // Maybe save this: deviceUuid.toString()); to the preferences.
	}
	
	private String generateMD5(String pw){
    	String password = pw;
    	 
        MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        md.update(password.getBytes());
 
        byte byteData[] = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
	}
        return sb.toString();
	}
	
	
	
	public void createTakenDialog(){
		Progressdialog.dismiss();
		final AlertDialog.Builder takenDialog = new AlertDialog.Builder(this);

		takenDialog.setTitle("Sorry");
		takenDialog.setMessage("Sorry your desired Username is already taken please try again");

		
		
		

		takenDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
			createStartupDialog();
			
		  }
		});
		
		MultiplayerStartupActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				takenDialog.show();
			}
		});

	}

	
	public void createDoneDialog(){
		Progressdialog.dismiss();
		final AlertDialog.Builder doneDialog = new AlertDialog.Builder(this);

		doneDialog.setTitle("Success");
		doneDialog.setMessage("You successfully registered");

		
		
		

		doneDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
			createStartupDialog();
		  }
		});
		
		MultiplayerStartupActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				doneDialog.show();
			}
		});

	}

	public void createFailureDialog(){
		Progressdialog.dismiss();
		final AlertDialog.Builder failDialog = new AlertDialog.Builder(this);

		failDialog.setTitle("Failure");
		failDialog.setMessage("Something went wrong ... Whatever you did try again in a few minutes");

		
		
		

		failDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
			createStartupDialog();
			
		  }
		});
		
		MultiplayerStartupActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				failDialog.show();
			}
		});

	}
	
	private void createStartupDialog(){
		
		
		Map<String, File> externalLocations = ExternalStorage
				.getAllStorageLocations();

		
		File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
		
		File loginFile = new File(sdCard + "/Quizzer/login.txt");
		
		String[] loginData = new String[2];
		int index = 0;
		
		try {
			BufferedReader in = new BufferedReader(new FileReader(loginFile.getPath()));
			String zeile = null;
			while ((zeile = in.readLine()) != null) {
				String data  = zeile.substring(0, zeile.length());
				
				loginData[index] = data;
				index++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
		AlertDialog.Builder loginDialog = new AlertDialog.Builder(this);

		loginDialog.setTitle("Quizzer Login");
		loginDialog.setMessage("In order to compete in Quizzer online games you must log in. \n \n If you don't " +
				"have an account provide a username and a password and hit the Register button ");

		LinearLayout layout = new LinearLayout(getApplicationContext());
		layout.setOrientation(1);
		// Set an EditText view to get user input 
		final EditText name = new EditText(this);
		
		if(loginData[0]!=null){
		name.setText(loginData[0]);
		}else{
		name.setText("Loginname");
		}
		
		final EditText pw = new EditText(this);
		
		if(loginData[1] != null){
		pw.setText(loginData[1]);	
		}else{
		pw.setText("Loginpassword");
		}
		
		final CheckBox box = new CheckBox(this);
		box.setText("Remember me !");
		box.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(box.isChecked()){
					savelogin=true;
				}else{
					savelogin = false;
				}
				
			}
		});

		
		layout.addView(name);
		layout.addView(pw);
		layout.addView(box);
		loginDialog.setView(layout);
		loginDialog.setCancelable(false);
		
		
		

		loginDialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
			String _name = name.getText().toString();
			String _pw = pw.getText().toString();
			if(savelogin){
				saveLoginToDisk(_name, _pw);
			}
			
			String RequestString = "LOGIN;" + _name +";" + generateMD5(_pw);
			// TODO Auto-generated method stub
			
			 Progressdialog = ProgressDialog.show(MultiplayerStartupActivity.this, "", 
                     "Log in. Please wait...", true);
			
			MultiplayerNetworkThread registerThread = new MultiplayerNetworkThread("LOGIN",RequestString,getApplicationContext(),MultiplayerStartupActivity.this);
			registerThread.start();
			
			startLoginTimer();
			
			
		  }
		});

		loginDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		  public void onClick(DialogInterface dialog, int whichButton) {
		    // Canceled.
				Intent myIntent = new Intent(getBaseContext(), QuizzerStartupActivity.class);
				myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(myIntent);
		  }
		});
		
		loginDialog.setNeutralButton("Register", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String _name = name.getText().toString();
				String _pw = pw.getText().toString();
				String RequestString = "REGISTER;" + _name +";" + generateMD5(_pw) +";" + deviceUuid.toString();
				// TODO Auto-generated method stub
				
				
				MultiplayerNetworkThread registerThread = new MultiplayerNetworkThread("REGISTER",RequestString,getApplicationContext(),MultiplayerStartupActivity.this);
				registerThread.start();
				
				 Progressdialog = ProgressDialog.show(MultiplayerStartupActivity.this, "", 
                        "Registering. Please wait...", true);
				System.out.println("Progress created");
				
				startResponseTimer();
				
			}
		});

		loginDialog.show();
		// see http://androidsnippets.com/prompt-user-input-with-an-alertdialog	
		
	}
	
	private void createBannedDialog(){
		final AlertDialog.Builder bannedDialog = new AlertDialog.Builder(this);
		bannedDialog.setCancelable(false);
		bannedDialog.setTitle("Sorry");
		bannedDialog.setMessage("Sorry your account was suspended please contact us");

		
		
		

		bannedDialog.setPositiveButton("Back", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
			createStartupDialog();
			
		  }
		});
		
		MultiplayerStartupActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				bannedDialog.show();
			}
		});
	}
	
	
	
	private void createNoMatchDialog(){
		final AlertDialog.Builder matchDialog = new AlertDialog.Builder(this);
		matchDialog.setCancelable(false);
		matchDialog.setTitle("Sorry");
		matchDialog.setMessage("Sorry the given login information do not match please try again");

		
		
		

		matchDialog.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
			createStartupDialog();
			
		  }
		});
		
		MultiplayerStartupActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				matchDialog.show();
			}
		});
	}
	
	private void createSuccessfullLoginDialog(){
		
		final AlertDialog.Builder succDialog = new AlertDialog.Builder(this);

		succDialog.setTitle("Success");
		succDialog.setMessage("You successfilly loged in");

		
		
		

		succDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
			//createStartupDialog();
			slidemenu.init(MultiplayerStartupActivity.this, R.menu.slide, MultiplayerStartupActivity.this, 333);
			slidemenu.setHeaderImage(getResources().getDrawable(R.drawable.ic_launcher));
			checkFriendlist();
		  }
		});
		
		MultiplayerStartupActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				succDialog.show();
			}
		});
	}
	
	
	
	private void startResponseTimer() {
		responseHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				if(((GlobalClass)getApplicationContext()).RegisterStatus == 0){
					createDoneDialog();
				}else if (((GlobalClass)getApplicationContext()).RegisterStatus == 1){
					createTakenDialog();
				}else if(((GlobalClass)getApplicationContext()).RegisterStatus == -1){
					createFailureDialog();
				}else{
					startResponseTimer();
				}
			}
		}, 1000);
	}
		
		
		private void startLoginTimer() {
			loginHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					if(((GlobalClass)getApplicationContext()).LoginStatus == 0){
						Progressdialog.dismiss();
						createSuccessfullLoginDialog();
					}else if (((GlobalClass)getApplicationContext()).LoginStatus == 1){
						Progressdialog.dismiss();
						createNoMatchDialog();
					}else if(((GlobalClass)getApplicationContext()).LoginStatus == 2){
						Progressdialog.dismiss();
						createBannedDialog();

                    }else if(((GlobalClass)getApplicationContext()).LoginStatus == (-1)){
                        Progressdialog.dismiss();
                        createFailureDialog();

					}else{
						startLoginTimer();
					}
				}
			}, 1000);
	}
		
		
		private void addSlidemenuItem(int MYITEMID, String text){
			// this demonstrates how to dynamically add menu items
			SlideMenuItem item = new SlideMenuItem();
			item.id = MYITEMID;
			item.icon = getResources().getDrawable(R.drawable.ic_launcher);
			item.label = text;
			slidemenu.addMenuItem(item);
		}

		@Override
		public void onSlideMenuItemClick(int itemId) {
			// TODO Auto-generated method stub
			
			if(itemId == R.id.addFriend){
				createAddFriendDialog();
			}else{
			
			createChallangeDialog(itemId);
			}
		}
	
	private void createAddFriendDialog() {
		final AlertDialog.Builder addFriendDialog = new AlertDialog.Builder(this);

		final EditText name = new EditText(this);
		name.setText("Friend's name");
		
		addFriendDialog.setView(name);
		
		addFriendDialog.setTitle("Add a Friend");
		addFriendDialog.setMessage("Please enter your friend's name");

		
		
		

		addFriendDialog.setPositiveButton("Search for Friend", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
				checkFriend(name.getText().toString().trim());
		  }
		});
		
		MultiplayerStartupActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				addFriendDialog.show();
			}
		});
			
		}

	private void createChallangeDialog(int itemId){
		
	}
	
	private void checkFriendlist(){
		Map<String, File> externalLocations = ExternalStorage
				.getAllStorageLocations();
		File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
		
		File friends = new File(sdCard + "/Quizzer/friends.txt");
		
	}

	
	private void checkFriend(String name){
		MultiplayerNetworkThread checkFriendThread = new MultiplayerNetworkThread("CHECKFORFRIEND",name,getApplicationContext(),MultiplayerStartupActivity.this);
		checkFriendThread.start();
		
		
		
	}
	
	protected void addFriendToMap(String name , int login){
		
		if(login != (-1)){
		friendMap.put(name, login);
		addSlidemenuItem(friendPosition, name+"  ,"+"    Last Login: "+String.valueOf(login));
		friendPosition++;
			createFriendFoundDialoge();
			
		}else if(login == (-2)){
			createFailureDialog();
		}else{
			createFriendNotFoundDialog();
		}
	}
	
	private void createFriendNotFoundDialog() {
		// TODO Auto-generated method stub
		final AlertDialog.Builder friendNotFoundDialog = new AlertDialog.Builder(this);

		friendNotFoundDialog.setTitle("Username does not exist");
		friendNotFoundDialog.setMessage("Sorry the given username does not exist");

		
		
		

		friendNotFoundDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
			//createStartupDialog();

		  }
		});
		
		MultiplayerStartupActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				friendNotFoundDialog.show();
			}
		});
		
	}

	private void createFriendFoundDialoge() {
		// TODO Auto-generated method stub
		final AlertDialog.Builder friendFoundDialog = new AlertDialog.Builder(this);

		friendFoundDialog.setTitle("Friend found");
		friendFoundDialog.setMessage("The User was added to your friendlist");

		
		
		

		friendFoundDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  // Do something with value!
			//createStartupDialog();
			writeFriendToDisk();

		  }
		});
		
		MultiplayerStartupActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				friendFoundDialog.show();
			}
		});
		
	}

	private void writeFriendToDisk(){
		Map<String, File> externalLocations = ExternalStorage
				.getAllStorageLocations();
		File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
		BufferedWriter bw = null;
		
		//File friends = new File(sdCard + "/Quizzer/friends.txt");
		
		clearLocationTXT(sdCard + "/Quizzer/friends.txt");
		
		try {
			 bw = new BufferedWriter(new FileWriter(new File(
					sdCard + "/Quizzer/friends.txt"), true));
			 for (String key : friendMap.keySet()) {
				 String entry = key+";" + friendMap.get(key).toString();
				 bw.write(entry);
				 bw.newLine();
			 }
			 bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
			
		
	}
	
	
	private void saveLoginToDisk(String name , String pw){
		Map<String, File> externalLocations = ExternalStorage
				.getAllStorageLocations();
		File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
		BufferedWriter bw = null;
		try {
			 bw = new BufferedWriter(new FileWriter(new File(
					sdCard + "/Quizzer/login.txt"), true));
			 
				 //String entry = key+";" + friendMap.get(key).toString();
				 bw.write(name);
				 bw.newLine();
				 bw.write(pw);
			 
			 bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	
	private void clearLocationTXT(String path){
		FileOutputStream writer;
		try {
			writer = new FileOutputStream(path);
			writer.write(0);
			writer.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
